//
//  UserDetailViewController.m
//  danpin
//
//  Created by chuangjia on 28/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "UserDetailViewController.h"
#import "CellConfig.h"
#import "viewconfig.h"
#import "SVPullToRefreshView+OY_PullRefreshView.h"
#import "BaseModel.h"
#import "ZToastManager.h"
#import "CommentViewController.h"
#import "OtherUserCenterVC.h"
#import "GoodConfig.h"
#import "ShareorderConfig.h"
#import "WebViewController.h"
@interface UserDetailViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)NSMutableArray *datasArray;
@property(nonatomic,strong)UITableView *tbView;
@property(nonatomic,assign)BOOL isLoadFinished;
@property(nonatomic,assign)BOOL isRequesting;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,assign)BOOL isRefresh;
@end

@implementation UserDetailViewController
@synthesize userid=_userid;
@synthesize action =_action;
@synthesize actionTitle=_actionTitle;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [UMengShare event:CK_USERDETAIL acc:[_userid integerValue]];
    self.isComment = YES;
    self.navTitle =_actionTitle;
    
    if (!_datasArray) {
        _datasArray =[[NSMutableArray alloc] init];
    }
    self.isLoadFinished =NO;
    self.isRequesting = NO;
    self.currentPage = 0;
    
    [self initUI];
   //   [ZShare showAnimationView:self.view center:CGPointZero];
    [self loadData:self.action];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc
{
    
}
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.navHeight, self.view.frame.size.width, self.view.frame.size.height-self.navHeight) style:UITableViewStylePlain];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor = [UIColor clearColor];
    _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tbView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_tbView];
    
    self.currentPage = 0;
    
    __weak typeof (self) wSelf = self;
    
    [_tbView addPullToRefreshWithActionHandler:^{
        wSelf.isRequesting = YES;
        wSelf.isRefresh = NO;
        wSelf.currentPage = 0;
        [wSelf.tbView.pullToRefreshView startAnimating];
        [wSelf  loadData:wSelf.action];
    }];
   //
    //
    [_tbView.pullToRefreshView setOYStyle];
//
    // setup infinite scrolling
    [self.tbView addInfiniteScrollingWithActionHandler:^{
        if (wSelf.isRequesting) {
            return ;
        }
        wSelf.isRefresh = NO;
        if (wSelf.isLoadFinished) {
            //停止菊花
            [wSelf.tbView.infiniteScrollingView stopAnimating];
            [wSelf.tbView setShowsInfiniteScrolling:NO];
            return;
        }
        [wSelf.tbView.infiniteScrollingView startAnimating];
        wSelf.currentPage =(int) [wSelf.datasArray count];
        [wSelf  loadData:wSelf.action];
        
    }];
    
    
}
#pragma mark - tableview
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_action isEqualToString:@"danpin"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [CategoryListCell returnCellHeight:dict];
    }else if ([_action isEqualToString:@"shaidan"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [CategoryListCell returnCellHeight:dict];
    }else if ([_action isEqualToString:@"like"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [CategoryListCell returnCellHeight:dict];
    }else if ([_action isEqualToString:@"comment"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [UserSayCell returnCellHeight:dict];
    }else if ([_action isEqualToString:@"follow"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [UserFollowCell returnCellHeight:dict];
    }else if ([_action isEqualToString:@"fans"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        return [UserFollowCell returnCellHeight:dict];
    }else if ([self.action isEqualToString:@"asking_recommend"])
    {
        NSDictionary *data =[self.datasArray objectAtIndex:indexPath.row];
        return [UserRecommendCell returnCellHeight:data];
    }else if ([self.action isEqualToString:@"score"])
    {
        NSDictionary *data =[self.datasArray objectAtIndex:indexPath.row];
        return [UserScoreCell returnCellHeight:data];
    }
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
   if ([_action isEqualToString:@"danpin"]) {
        CategoryListCell *cell = (CategoryListCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[CategoryListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"shaidan" indexPath:indexPath];
        return cell;
    }else if ([_action isEqualToString:@"shaidan"]) {
        CategoryListCell *cell = (CategoryListCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[CategoryListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"shaidan" indexPath:indexPath];
        return cell;
    }else if ([_action isEqualToString:@"like"]) {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
       CategoryListCell *cell = (CategoryListCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
            if(cell == nil)
            {
                cell = [[CategoryListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
                cell.backgroundColor=[UIColor clearColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
                
                __weak typeof (self) wSelf = self;
                [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                    [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
                }];
            }
            
            [cell showInfo:dict key:@"shaidan" indexPath:indexPath];
            return cell;
        
    }else if ([_action isEqualToString:@"comment"]) {
        
        UserSayCell *cell = (UserSayCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[UserSayCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"comment" indexPath:indexPath];
        return cell;
    }else if ([_action isEqualToString:@"follow"]) {
        
        UserFollowCell *cell = (UserFollowCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[UserFollowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"mefollow" indexPath:indexPath];
        return cell;
    }else if ([_action isEqualToString:@"fans"]) {
        
        UserFollowCell *cell = (UserFollowCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[UserFollowCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"fans" indexPath:indexPath];
        return cell;
    }else if ([self.action isEqualToString:@"asking_recommend"])
    {
        UserRecommendCell *cell = (UserRecommendCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[UserRecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"asking_recommend" indexPath:indexPath];
        return cell;
    }else if([self.action isEqualToString:@"score"])
    {
        UserScoreCell *cell = (UserScoreCell*)[tableView  dequeueReusableCellWithIdentifier:@""];
        if(cell == nil)
        {
            cell = [[UserScoreCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
            cell.backgroundColor=[UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _tbView.separatorStyle = UITableViewCellSeparatorStyleNone;
            __weak typeof (self) wSelf = self;
            [cell setCallBack:^(BEventType t, UIView *v,id obj,id key,NSIndexPath *indexPath) {
                [wSelf cellAction:t views:v obj:obj key:key indexPath:indexPath];
            }];
        }
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        [cell showInfo:dict key:@"score" indexPath:indexPath];
        return cell;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row>=self.datasArray.count) {
        return;
    }
    if ([_action isEqualToString:@"danpin"]||[_action isEqualToString:@"shaidan"]||[_action isEqualToString:@"like"])
    {
        NSDictionary *dict =[self.datasArray objectAtIndex:indexPath.row];
        int is_shaidan =[[dict objectForKey:@"is_shaidan"] intValue];
        if (is_shaidan==1)
        {
            ShaiorderDetailViewController *good =[[ShaiorderDetailViewController alloc] init];
            good.type =-1;
            good.dictionary = dict;
            good.photo_id = [NSString stringWithFormat:@"%@",[dict objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
            good=nil;
        }else if (is_shaidan==20) {
            WebViewController *web =[[WebViewController alloc] init];
            web.titlestr=@"user";
            NSString *urlstr =[dict objectForKey:@"url"];
            web.jsonUrl = urlstr;
            [self.navigationController pushViewController:web animated:YES];
            web=nil;
            
        }else{
            GoodViewController *good =[[GoodViewController alloc] init];
            good.type =-1;
            good.dictionary =dict;
            good.photo_id = [NSString stringWithFormat:@"%@",[dict objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
        }
        
    }else if ([self.action isEqualToString:@"comment"]) {
        NSDictionary *data =[self.datasArray objectAtIndex:indexPath.row];
        NSDictionary *ware =[data objectForKey:@"ware"];
        int isShaidan = [[ware objectForKey:@"is_shaidan"] intValue];
        if (isShaidan==1) {
            ShaiorderDetailViewController *good =[[ShaiorderDetailViewController alloc] init];
            good.type =-1;
            good.dictionary = ware;
            good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
            good=nil;
        }else if (isShaidan==20) {
            WebViewController *web =[[WebViewController alloc] init];
            web.titlestr=@"user";
            NSString *urlstr =[ware objectForKey:@"url"];
            web.jsonUrl = urlstr;
            [self.navigationController pushViewController:web animated:YES];
            web=nil;
            
        }else
        {
            GoodViewController *good =[[GoodViewController alloc] init];
            good.type =-1;
            good.dictionary =ware;
            good.photo_id = [NSString stringWithFormat:@"%@",[ware objectForKey:@"photo_id"]];
            [self.navigationController pushViewController:good animated:YES];
        }
        
    }else if ([self.action isEqualToString:@"follow"]||[self.action isEqualToString:@"fans"]) {
        NSDictionary *data =[self.datasArray objectAtIndex:indexPath.row];
        OtherUserCenterVC *user =[[OtherUserCenterVC alloc] init];
        NSMutableDictionary *dict =[NSMutableDictionary dictionary];
        NSString *largeFace = [[NSString stringWithFormat:@"%@",[data objectForKey:@"largeFace"]] replaceNullString];
        [dict setValue:largeFace forKey:@"largeFace"];
        if ([self.action isEqualToString:@"fans"]) {
            
            NSString *fans_id = [[NSString stringWithFormat:@"%@",[data objectForKey:@"fans_id"]] replaceNullString];
             [dict setValue:fans_id forKey:@"user_id"];
        }else{
            
            NSString *follow_id = [[NSString stringWithFormat:@"%@",[data objectForKey:@"follow_id"]] replaceNullString];
            [dict setValue:follow_id forKey:@"user_id"];
        }
        
        NSString *nick_name = [[NSString stringWithFormat:@"%@",[data objectForKey:@"nick_name"]] replaceNullString];
        [dict setValue:nick_name forKey:@"nick_name"];
        user.userDictionary=dict;
        [self.navigationController pushViewController:user animated:YES];
        
    }else if ([self.action isEqualToString:@"asking_recommend"])
    {
        NSDictionary *data =[self.datasArray objectAtIndex:indexPath.row];
        GoodViewController *good =[[GoodViewController alloc] init];
        good.type =-1;
        good.dictionary =data;
        good.photo_id = [NSString stringWithFormat:@"%@",[data objectForKey:@"photo_id"]];
        [self.navigationController pushViewController:good animated:YES];
    }
}

-(void)cellAction:(BEventType)type views:(UIView *)v obj:(id)obj key:(id)key indexPath:(NSIndexPath *)indexPath
{
    switch (type) {
        case BEventType_comment:
        {
            NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"photo_id"]];
            CommentViewController *comm =[[CommentViewController alloc] init];
            comm.photo_id =pid;
            comm.dictionary =obj;
            [self.navigationController pushViewController:comm animated:YES];
        }
            break;
        case BEventType_like:
        {
            NSString *pid =[NSString stringWithFormat:@"%@",[obj objectForKey:@"photo_id"]];
            if ([self isLogin]) {
                [self likeWithPid:pid indexPath:indexPath];
            }
        }
            break;
        case BEventType_userfollow:
        {
            if ([self isLogin]){
                NSString *pid =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"follow_id"]] replaceNullString];
                if(pid.length==0)
                {
                    pid =[[NSString stringWithFormat:@"%@",[obj objectForKey:@"fans_id"]] replaceNullString];
                }
                NSString *nickname =[NSString stringWithFormat:@"%@",[obj objectForKey:@"nick_name"]];
                NSMutableDictionary *dict =[NSMutableDictionary dictionary];
                [dict setValue:@"follow_user" forKey:@"action"];
                [dict setValue:@"" forKey:@"brand_id"];
                [dict setValue:@"" forKey:@"cate_id"];
                [dict setValue:pid forKey:@"follow_id"];
                [dict setValue:nickname forKey:@"follow_name"];
                [dict setValue:@"" forKey:@"tag"];
                __weak typeof (self) wSelf = self;
                [BaseModel follow:dict success:^(AFHTTPRequestOperation* operation, id result){
                    
                    if (result&&[result isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *resultDist =(NSDictionary*)result;
                        [[ZToastManager ShardInstance] showtoast:[resultDist objectForKey:@"msg"]];
                        [wSelf.datasArray removeObjectAtIndex:indexPath.row];
                        [wSelf.tbView reloadData];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateLoveList" object:pid];
                    }
                    
                } failure:^(NSError* error){
                    [[ZToastManager ShardInstance] showtoast:@"取消关注失败"];
                }];
            }
        }
            break;
        case BEventType_qiugou:
        {
           
        }
            break;
        default:
            break;
    }
}
//喜欢
-(void)likeWithPid:(NSString*)pid  indexPath:(NSIndexPath*)indexPath
{
    [UMengShare event:CK_LOVE acc:1];
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:pid forKey:@"photo_id"];
    [BaseModel love:dict success:^(AFHTTPRequestOperation *operation, id result) {
        int code =  [[result objectForKey:@"code"] intValue];
        NSString *like_cnt =  [NSString stringWithFormat:@"%@",[result objectForKey:@"like_cnt"]];
        if (code==1 || code==2) {
            for (int i=0; i<[wSelf.datasArray count]; i++) {
                NSDictionary *dict =[wSelf.datasArray objectAtIndex:i];
                if ([dict isKindOfClass:[NSDictionary class]]) {
                    NSString *pidd =[NSString stringWithFormat:@"%@",[dict objectForKey:@"photo_id"]];
                    if ([pidd isEqualToString:pid]) {
                        NSMutableDictionary *temp = [dict mutableCopy];
                        if (code==1) {
                            [temp setValue:@"1" forKey:@"like"];
                        }else{
                            [temp setValue:@"0" forKey:@"like"];
                        }
                        [temp setValue:like_cnt forKey:@"like_cnt"];
                        [wSelf.datasArray replaceObjectAtIndex:i withObject:temp];
                        break;
                    }
                }
            }
            [self.tbView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
        
    } failure:^(NSError *error) {
    //    [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}

-(void)loadData:(NSString*)action
{
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:action forKey:@"action"];
    [dict setValue:[NSString stringWithFormat:@"%@",self.userid] forKey:@"user_id"];
      [dict setValue:[NSString stringWithFormat:@"%@",[ZShare sharedInstance].getUserNickname] forKey:@"user_name"];
    [dict setValue:[NSString stringWithFormat:@"%d",self.currentPage] forKey:@"from"];
    __weak typeof (self) wSelf = self;

    wSelf.isRequesting = YES;
    [BaseModel homeV1:dict allowFetchCache:NO success:^(AFHTTPRequestOperation *operation, id result) {
        [wSelf parserResultObject:result];
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    //    [ZShare hiddenAnimationView:wSelf.view];
    } failure:^(NSError *error) {
        wSelf.isRequesting = NO;
        wSelf.isRefresh =NO;
        [wSelf.tbView.pullToRefreshView stopAnimating];
        [wSelf.tbView.infiniteScrollingView stopAnimating];
    //    [ZShare hiddenAnimationView:wSelf.view text:@""];
    }];
}
-(void)parserResultObject:(id)resultObject
{
    [[ZToastManager ShardInstance] hideprogress];
    if (resultObject==nil) {
        return;
    }
    if (resultObject && [resultObject isKindOfClass:[NSDictionary class]]) {
        id data =  [resultObject objectForKey:@"data"];
        if (data && [data isKindOfClass:[NSArray class]]){
            if (self.currentPage==0) {
                [self.datasArray removeAllObjects];
            }
            for (id dict in data) {
                [self.datasArray addObject:dict];
            }
        }
        id no_data =  [resultObject objectForKey:@"no_data"];
        if (no_data&&[no_data isKindOfClass:[NSString class]]) {
       //     [ZShare hiddenAnimationView:self.view text:no_data];
            self.tbView.tableFooterView =nil;
        }else {
        //    [ZShare hiddenAnimationView:self.view];
        }
        self.isLoadFinished =  [[resultObject objectForKey:@"end"] boolValue];
        
        if (self.isLoadFinished) {
            
            NSString *end_msg =[resultObject objectForKey:@"end_msg"];
            self.tbView.tableFooterView =[ZShare footerView:end_msg];
            
            [self.tbView.infiniteScrollingView stopAnimating];
            [self.tbView setShowsInfiniteScrolling:NO];
        }
    }
    [self.tbView reloadData];
    self.isRequesting = NO;
}
@end
